import { useState, useEffect } from 'react'
import { Dropdown, Menu, Popover, Typography } from 'antd'
import { InbizIcon } from '@inbiz/utils';
import { TextWidget } from '@inbiz/react';
import './index.less'
export default function SortArea(props) {
  const { config, handleSortChange, params } = props
  // 排序弹窗
  const [sortVisible, $sortVisible] = useState(false)
  // 显示升序降序的弹窗
  const [visibleInfo, $visibleInfo] = useState(-1)
  // 选中的排序的名称
  const [selectedIndex, $selectedIndex] = useState(0)
  // 这个属性是后加的
  const [order, $order] = useState(params.Order)
  
  const sortField = config?.sortField.filter(item => item.enable) || []
  const [sortValue, $sortValue] = useState(sortField?.[0]?.IndexFieldDesc || sortField?.[0]?.IndexFieldName || 'SearchResultEngine.matchingDegree')

  useEffect(() => {
    const sessionSort = sessionStorage.getItem(`${config.IndexName}_searchSortData`)
      let newsessionSort = {}
      if (sessionSort) {
        newsessionSort = JSON.parse(sessionSort)
        $sortValue(newsessionSort.sortname || 'SearchResultEngine.matchingDegree')
        $order(newsessionSort.order)
        const i = sortField.findIndex(ele => ele.IndexFieldName == newsessionSort.IndexFieldName)
        $selectedIndex(i)
      } else {
        $sortValue(sortField?.[0]?.IndexFieldDesc || sortField?.[0]?.IndexFieldName || 'SearchResultEngine.matchingDegree')
      }
  }, [config])

  const changeSort = (e, order, index) => {
    $visibleInfo(-1)
    $order(order)
    $sortVisible(false)
    $selectedIndex(index)
    $sortValue(e.IndexFieldDesc || e.IndexFieldName)
     // 改变排序不改变切面, 所以注释, 以前排序在右侧上面, 所以改变排序要改变切面
    // categoryLevel.current = -1
    handleSortChange({
      IndexFieldName: e.default ? '' : e.IndexFieldName,
      order,
    })
    sessionStorage.removeItem(`${config.IndexName}_searchSortData`)
    sessionStorage.setItem(`${config.IndexName}_searchSortData`, JSON.stringify({
      IndexFieldName: e.default ? '' : e.IndexFieldName,
      order,
      sortname: e.IndexFieldDesc || e.IndexFieldName
    }))
  }
  const content = (ele, index) => {
    return <>
      <div className={`${selectedIndex == index && order == 'asc' ? 'selectsort' : ''}`} onClick={(e) => {
        e.stopPropagation()
        changeSort(ele, 'asc', index)
      }}>
        <TextWidget>SearchResultEngine.ascendingOrder</TextWidget>
      </div>
      <div className={`${selectedIndex == index && order == 'desc' ? 'selectsort' : ''}`} onClick={(e) => {
        e.stopPropagation()
        changeSort(ele, 'desc', index)
      }}>
        <TextWidget>SearchResultEngine.descendingOrder</TextWidget>
      </div>
    </>
  }
  const menu = <Menu>
    {
      sortField.map((ele, index) => {
        return <Menu.Item
          key={ele.IndexFieldDesc || ele.IndexFieldName}
          className={`${selectedIndex == index ? 'selectname' : ''}`}
          onMouseEnter={() => {
            $visibleInfo(index)
          }}
        >
          <Popover
            placement="rightTop"
            visible={visibleInfo == index}
            content={() => content(ele, index)}
            overlayClassName='sortName'
          >
            <div style={{ width: '100%', }}>
              <InbizIcon
                type='icon-ic-select-bold'
                className='checkIcon'
                style={{ fontSize: 15, marginRight: 5 }}
              />
              <Typography.Text ellipsis title={ele.IndexFieldDesc || ele.IndexFieldName} style={{ width: '100%', maxWidth: 85 }}>{ele.IndexFieldDesc || ele.IndexFieldName}</Typography.Text>
            </div>
          </Popover>
        </Menu.Item>
      })
    }
  </Menu>


  if (sortField.length == 0) {
    return null
  }
  return (
    <div className='sortArea'>
      <Dropdown
        overlay={menu}
        visible={sortVisible}
        trigger={['click']}
        overlayClassName='sortDropDown'
        onVisibleChange={(bool) => {
          $visibleInfo(-1)
          $sortVisible(bool)
        }}>
        <div className='sortTitle'  title={sortValue}>
          {order == 'asc' && <InbizIcon type='icon-paixu-shengxu' style={{ fontSize: 16, marginRight: 5 }} />}
          {order == 'desc' && <InbizIcon type='icon-paixu-jiangxu' style={{ fontSize: 16, marginRight: 5 }} />}
          <TextWidget>SearchResultEngine.sort</TextWidget>
          <span>：</span>
          <span> <TextWidget>{sortValue}</TextWidget> </span>
        </div>
      </Dropdown>
    </div>
  )
}
